import { SetSiteRemarkModalComponent } from './set-site-remark-modal/set-site-remark-modal.component';
import { AppComponentBase } from '@shared/common/app-component-base';
import { UserInfoDTO, DictionaryDTO } from '@shared/service-proxy/service-proxies';
import { Component, OnInit, ViewChild, Injector } from '@angular/core';
import {
  FormBuilder,
  FormControl,
  FormGroup,
  Validators
} from '@angular/forms';
import { ServiceProxy, SiteDTO } from '@shared/service-proxy/service-proxies';
import { NzMessageService } from 'ng-zorro-antd';
import { MapCircleModalComponent } from '../map-circle-modal/map-circle-modal.component';
import { NzTableHelper } from '@shared/helpers/NzTableHelper';
import { finalize } from 'rxjs/operators';
import { FileUploader } from 'ng2-file-upload';
import { AppConsts } from '@shared/AppConsts';

@Component({
  selector: 'app-site-management',
  templateUrl: './site-management.component.html',
  styleUrls: ['./site-management.component.less']
})
export class SiteManagementComponent extends AppComponentBase implements OnInit {
  uploader: FileUploader;

  @ViewChild('mapCircleModal') mapCircleModal: MapCircleModalComponent;
  @ViewChild('setSiteRemarkModal') setSiteRemarkModal: SetSiteRemarkModalComponent;
  @ViewChild('fileSelect') uploadImg: any;
  tableHelper: NzTableHelper;
  site: SiteDTO = new SiteDTO();
  loading: boolean = true;
  keyword: string = '';
  siteType: string = '';
  isVisible = false;
  isOkLoading = false;
  validateForm: FormGroup;
  siteTypes: DictionaryDTO[] = [];
  title: string;
  users: UserInfoDTO[] = [];

  constructor(injector: Injector, private fb: FormBuilder, private _service: ServiceProxy) {
    super(injector);
    this.tableHelper = new NzTableHelper();
  }

  ngOnInit() {
    this.validateForm = this.fb.group({
      siteName: [null, [Validators.required,Validators.maxLength(255)]],
      // address: [null, [Validators.required]],
      managerId: [null, [Validators.nullValidator]],
      managerPhone: [null, [Validators.nullValidator,Validators.maxLength(20)]],
      sitePhone: [null, [Validators.required,Validators.maxLength(20)]],
      siteType: [null, [Validators.required]],
      lat: [null, [Validators.required]],
      lng: [null, [Validators.required]],
      // radius: [null, [Validators.required]]
    });
    this.siteType = '';
    this.getUsers();
    this.getSiteTypes();
    this.load();
    this.initUploaders();
  }

  load(pageIndex?: number) {
    if (typeof pageIndex !== 'undefined') {
      this.tableHelper.pageIndex = pageIndex || 1;
    }
    this.getList();
  }

  sort(sort: { key: string, value: string }): void {
    this.tableHelper.setSorting = sort;
    this.load();
  }

  getList() {
    this._service.getPageSitesUsingGET(this.tableHelper.pageIndex, this.tableHelper.pageSize, this.keyword, this.siteType).pipe(finalize(() => {
      this.tableHelper.loading = false;
    })).subscribe((result) => {
      this.tableHelper.items = result.result.fieldList;
      this.tableHelper.totalCount = result.result.totalRow;
    });
  }


  getUsers() {
    this._service.getAllUserInfoListUsingGET().subscribe(result => {
      this.users = result.result.fieldList;
    });
  }

  getSiteTypes() {
    this._service.getDictionaryByDictionaryTypeUsingGET('site_type').subscribe(result => {
      this.siteTypes = result.result.fieldList;
    });
  }

  reset() {
    this.tableHelper.pageIndex = 1;
    this.keyword = '';
    this.siteType = '';
    this.load();
  }

  showModal(siteId?: string): void {
    this.site = new SiteDTO();
    if (siteId) {
      this.title = this.l('edit');
      this._service.getSiteUsingGET(siteId).subscribe(result => {
        this.site = result.result;
        this.isVisible = true;
      });
    } else {
      this.validateForm.reset();
      this.title = this.l('create');
      this.isVisible = true;
    }
  }

  checkLong(lng: number): boolean {
    if(!lng){
      return false;
    }
    var lngStr = lng.toString();
    
    var longrg = /^(\-|\+)?(((\d|[1-9]\d|1[0-7]\d|0{1,3})\.\d{0,6})|(\d|[1-9]\d|1[0-7]\d|0{1,3})|180\.0{0,6}|180)$/;

    if (!longrg.test(lngStr)) {
      this.message.error('经度整数部分为0-180,小数部分为0到6位!');
      return false
    }
    return true;
  }
  checkLat(lat: number): boolean {
    if(!lat){
      return false
    }
    var latStr = lat.toString();
    var latreg = /^(\-|\+)?([0-8]?\d{1}\.\d{0,6}|90\.0{0,6}|[0-8]?\d{1}|90)$/;
    if (!latreg.test(latStr)) {
      this.message.error(this.l('verify_failed_please_check_the_form_item'));//'纬度整数部分为0-90,小数部分为0到6位!');
      return false;
    }
    return true;
  }

  handleOk(): void {
    this.isOkLoading = true;
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
      this.validateForm.controls[i].updateValueAndValidity();
    }

    if (this.checkLong(this.site.lng) && this.checkLat(this.site.lat)) {
      if (this.validateForm.valid) {
        if (this.site.id) {
          this._service.updateSiteUsingPUT(this.site, this.site.id).subscribe(result => {
            this.isOkLoading = false;
            if (result.success) {
              this.message.success(this.l('save_success'));
              this.load();
              this.isVisible = false;
            } else {
              this.message.info(this.l(result.error.message));
            }
          }, error => {
            this.isOkLoading = false;
            this.message.error(error.message);
          });
        } else {
          this._service.createSiteUsingPOST(this.site).subscribe(result => {
            this.isOkLoading = false;
            if (result.success) {
              this.message.success(this.l('save_success'));
              this.load();
              this.isVisible = false;
            } else {
              this.isOkLoading = false;
              this.message.info(this.l(result.error.message));
            }
          }, error => {
            this.isOkLoading = false;
            this.message.error(error.message);
          });
        }
      } else { // 验证未通过
        this.isOkLoading = false;
        this.message.error(this.l('verify_failed_please_check_the_form_item'));
      }
    }
    else {
      this.isOkLoading = false;
    }
  }

  handleUsing(site: SiteDTO) {
    this.setSiteRemarkModal.show(site.id, site.enableFlag);
  }

  handleCancel(): void {
    this.isVisible = false;
  }

  showMap(data: SiteDTO) {
    this.mapCircleModal.show(data.lng, data.lat, data.radius);
  }

  changeUser() {
    const user = this.users.find(m => m.id == this.site.managerId);
    if (user) {
      this.site.managerPhone = user.phone;
    }
  }

  initUploaders(): void {
    this.uploader = new FileUploader({
      url: AppConsts.serverBaseUrl + '/api/siiat/v1/sites/batchImport',
      method: 'POST',
      authToken: 'Bearer ' + abp.auth.getToken(),
      removeAfterUpload: true,
      autoUpload: true
    });
    this.uploader.onAfterAddingFile = (file) => {
      file.withCredentials = false;
    };

    this.uploader.onSuccessItem = (item, response, status) => {
      const ajaxResponse = JSON.parse(response);
      if (ajaxResponse.success) {
        this.message.success(this.l('upload_success'));
      } else {
        this.message.error(this.l(ajaxResponse.error.message));
      }

      this.uploader.destroy();
      this.initUploaders();
      this.imgCropper();
      this.load();

    };
    this.uploader.onErrorItem = (item, response, status) => {
      const ajaxResponse = JSON.parse(response);
      this.message.error(this.l(ajaxResponse.error.message));
      this.imgCropper();
    };
  }
  imgCropper() {
    // 一系列操作
    // 最后把input的value置空
    this.uploadImg.nativeElement.value = '';
  }
}
